<template>
  <div>
    <el-form ref="ruleForm" :model="formdata" :rules="formrules" label-width="100px" label-suffix=":">
      <el-row>
        <el-col :span="calcWidth(item)" v-for="(item, index) in formobj" :key="item.key" >
          <el-form-item :label="item.label" :prop="item.key">
        <el-input
          v-if="item.type == 'input'"
          v-model="formdata[item.key]"
          auto-complete="new-password"
          :disabled="item.disabled ? item.disabled : false"
          :placeholder="'请输入' + item.label"
        />
        <el-radio-group v-if="item.type == 'radio'" v-model="formdata[item.key]">
          <el-radio v-for="n in item.options" :label="n.value">{{ n.label }}</el-radio>
        </el-radio-group>
        <el-input
          v-else-if="item.type == 'password'"
          v-model="formdata[item.key]"
          auto-complete="new-password"
          type="password"
          :disabled="item.disabled ? item.disabled : false"
          :placeholder="'请输入' + item.label"
        />
        <el-input
          v-else-if="item.type == 'textarea'"
          v-model="formdata[item.key]"
          type="textarea"
          :placeholder="'请输入' + item.label"
          :rows="5"
        />
        <!-- 上传图片 -->
        <el-upload
          v-else-if="item.type == 'upload'"
          class="upload-demo"
          :action="ftpupload + '/fileApi/upload'"
          :on-success="
            function (res, file, fileList) {
              return handleSuccess(res, file, fileList, item.key);
            }
          "
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :limit="1"
          :on-change="
            function (file, fileList) {
              return handleChange(file, fileList, item.key);
            }
          "
          :before-upload="beforeUpload"
          :on-exceed="handleExceed"
          :file-list="[fliedata[item.key]]"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
        <!-- 上传视频 -->
        <el-upload
          v-else-if="item.type == 'video'"
          class="upload-demo"
          :on-exceed="handleExceed"
          :action="ftpupload + '/fileApi/upload'"
          :on-change="function (res, file) {
            return handlevideoChange(res, file, item.key);
          }"
          :before-upload="beforemp4Upload"
          :file-list="fileList"
          :limit="1"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">{{ item.word }}</div>
        </el-upload>
        <el-upload
          v-else-if="item.type == 'execl'"
          class="upload-demo"
          :action="ftpupload + '/fileApi/upload'"
          :on-change="function (res, file) {
            return handleexeclChange(res, file, item.key);
          }"
          :file-list="fileList"
          multiple
          :limit="100"
          :on-remove="(res, file)=>{
            return handexeclleRemove(res, file,item.key)
          }"
          :auto-upload="true"
          :on-success="handle_success"
        >
          <el-button size="small" type="primary">附件上传</el-button>
          <div slot="tip" class="el-upload__tip">{{ item.word }}</div>
        </el-upload>
        <!-- 上传图片带预览 -->
        <el-upload
          v-else-if="item.type == 'pic'"
          class="avatar-uploader"
          :action="ftpupload + '/fileApi/upload'"
          :show-file-list="false"
          :on-success="
            function (res, file) {
              return handleAvatarSuccess(res, file, item.key);
            }
          "
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="picshow" :src="'/show' + formdata[item.key]" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>

        <!-- 多图上传 -->
        <el-upload
          v-else-if="item.type == 'mpic'"
          :action="ftpupload + '/fileApi/upload'"
          list-type="picture-card"
          :on-success="
            function (res, file) {
              return handlemSuccess(res, file, item.key);
            }"
          :on-remove="
            function (res, file) {
              return handlemRemove(res, file, item.key);
            }"
          :before-upload="beforeAvatarUpload"
          :file-list="formdata[item.key]"
        >
          <i class="el-icon-plus" />
        </el-upload>

        <!-- 多图上传list形式 -->
        <el-upload
          v-else-if="item.type == 'piclist'"
          class="upload-demo"
          :action="ftpupload + '/fileApi/upload'"
          :on-success="
            function (res, file) {
              return handlepiclistAvatarSuccess(res, file, item.key);
            }
          "
          :on-remove="
            function (res, file) {
              return handlempiclistRemove(res, file, item.key);
            }"
          :before-upload="beforeAvatarUpload"
          :file-list="fileListfileList"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>

        <!-- 下拉列表 -->
        <el-select
          v-else-if="item.type == 'select'"
          v-model="formdata[item.key]"
          filterable
          :placeholder="'请选择' + item.label"
          :disabled="item.disabled ? item.disabled : false"
          @change="changelanmu"
        >
          <el-option v-for="item in item.options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-select
          v-else-if="item.type == 'multipleselect'"
          v-model="formdata[item.key]"
          multiple
          :placeholder="'请选择' + item.label"
        >
          <el-option v-for="item in item.options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <!-- r日期 -->
        <el-date-picker
          class="myDateStyle"
          v-else-if="item.type == 'date'"
          v-model="formdata[item.key]"
          :placeholder="'请选择' + item.label"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
        />
        <!-- 多选 -->
        <el-checkbox-group v-else-if="item.type == 'check'" v-model="formdata[item.key]" size="medium">
          <el-checkbox-button v-for="item in item.options" :key="item.value" :label="item.label">{{ item.label }}
          </el-checkbox-button>
        </el-checkbox-group>
        <el-radio-group v-else-if="item.type == 'radio'" v-model="formdata[item.key]">
          <el-radio-button v-for="item in item.options" :key="item.value" :label="item.value">{{ item.label }}
          </el-radio-button>
        </el-radio-group>
        <div v-else-if="item.type == 'text'">
          {{ formdata[item.key] }}
        </div>
        <div v-else-if="item.type == 'editor'">
          <Editor v-model="formdata[item.key]" :is-clear="isClear" @editorchange="editorchange($event, item.key)" />
        </div>
        <div v-else-if="item.type == 'editorManager'">
          <EditorManager v-model="formdata[item.key]" :is-clear="isClear" @editorchange="editorchange($event, item.key)" />
        </div>
        <div v-else-if="item.type == 'editor2'">
          <editorBase v-model="formdata[item.key]" :is-clear="isClear" @editorchange="editorchange($event, item.key)" />
        </div>
        <div v-else-if="item.type == 'tree'">
          <el-input v-model="treename" readonly @click.native="tree(item.key)" />
        </div>
      </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <el-dialog title="选择机构" :visible.sync="dialogVisible" width="30%" append-to-body>
      <el-tree :data="treedata" :props="defaultProps" node-key="id" default-expand-all @node-click="handleNodeClick" />
    </el-dialog>
  </div>
</template>
<script>
import E from 'wangeditor'
import { organizationApiqueryAll } from '@/api/organizationApir'
import Editor from '@/components/editor.vue'
import EditorManager from '@/components/editorManager.vue'
import editorBase from '@/components/editorBase.vue'
import { uploadApi } from '@/api/webpage'
import keyboardVue from '@/views/charts/keyboard.vue'
import { isArray } from '@/utils/validate'
export default {
  name: 'TableList',
  components: {
    Editor,
    editorBase,
    EditorManager
  },
  props: {
    formdata: {
      type: Object,
      default() {
        return {}
      }
    },
    formrules: {
      type: Object,
      default() {
        return {}
      }
    },
    formobj: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      picshow: false,
      fliedata: {},
      isClear: '',
      imageUrl: '',
      // ftpupload:''
      fileList: [],
      ftpupload: process.env.VUE_APP_BASE_HOST + process.env.VUE_APP_BASE_API,
      dialogVisible: false,
      treedata: [],
      params: {
        name: '',
        parentId: ''
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      lskey: '',
      treename: '',
      fileListfileList:[]
    }
  },
  watch: {
    formdata: {
      handler: function(val) {
        this.picshow = false // 初始化图片显示
        console.log("改变后的数据：",val)
        this.fileList = []
        if (val.fileUrl) {
          const arr = val.fileUrl.split(',')
          const arrname = val.fileName.split(',')
          console.log(arr,arrname)
          arr.forEach((item, i) => {
            if(item){
              this.fileList.push({
                name: arrname[i],
                url: item
              })
            }
          })
        }
        if(val.url){
          console.log("url=",val.url)
          this.picshow=true
          this.fileListfileList = val.url.split(',').map((item,index)=>{
            return { name: index, url: '/show' + item }
          })
        }
        if(val.urlss){
          let urls = val.urlss.split(",")
                 urls.map((item, index) => {
                  this.fileList.push({
                    name: item.replace("/",''),
                    url: '/show' + item
                  })
                })
        }
        if (val.listfile && val.listfile.length > 0) {
          val.listfile.forEach(item => {
            this.fileList.push({
              name: item.name,
              url: '/show' + item.url
            })
          })
        }
        console.log("文件列表：",this.fileList)
      }
    },
    formobj: {
      handler: function(val) {
        val.forEach(item => {
          if (item.type == 'pic') {
            if (this.formdata[item.key]) {
              this.picshow = true
              this.imageUrl = this.formdata[item.key]
            } else {
              this.imageUrl = ''
            }
          }
          // if (item.type == 'piclist') {
          //   if (this.formdata[item.key] && !isArray(this.formdata[item.key])) {
          //     let urls = (this.formdata[item.key] || "").split(",")
          //        urls.map((item, index) => {
          //         this.fileList.push({
          //           name: index, url: '/show' + item
          //         })
          //       })
          //   } else {
          //     this.fileList = []
          //   }
          // }
          /*if (item.type == 'video') {
            if (this.formdata[item.key]) {
              const name = this.formdata[item.key].split('.')[0].replace('/', '')
              this.fileList.push({
                name: name,
                url: this.formdata[item.key]
              })
            } else {
              this.fileList = []
            }
          }*/
        })
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getlist()
  },
  methods: {
    calcWidth(item){
      if(item.key == 'author'||item.key == 'postedBy'||item.key == 'no'){
        return 8;
      }else if(item.key == 'approvalResult'|| item.key == 'top'||item.key == 'nice'){
        return 4
      }
      return 24
    },
    changelanmu(val) {
      this.$emit('changelanmu', val)
    },
    handlepiclistAvatarSuccess(res,file,key){
      if(Array.isArray(this.formdata[key])){
        this.formdata[key].push(res.data[0].address.replace('\\', '/'))
      } else{
       let newArray = []
       this.formdata[key].split(',').map(item=>{
         newArray.push(item)
       })
       newArray.push(res.data[0].address.replace('\\', '/'))
       this.formdata[key] = newArray
      }



    },
    handlempiclistRemove(res,file,key){
      this.formdata[key] = file.map(item=>{
        if(item.response){
          return item.response.data[0].address.replace('\\', '/')
        }else{
          return item.url.replace('\\', '/')
        }

      })

    },



    handleNodeClick(val) {
      this.treename = val.name
      this.formdata[this.lskey] = val.id
      this.dialogVisible = false
    },
    transTree(list, rootValue) {
      const treeData = []
      list.forEach(item => {
        if (item.parentId === rootValue) {
          const children = this.transTree(list, item.id)
          if (children.length) {
            item.children = children
          }
          treeData.push(item)
        }
      })

      return treeData
    },
    getlist() {
      organizationApiqueryAll(this.params).then((res) => {
        if (res.code == 0) {
          this.treedata = this.transTree(res.data, null)
        }
      })
    },
    tree(key) {
      this.dialogVisible = true
      this.lskey = key
    },
    handle_success(res){
      // console.log('附件上传成功',res)
      // 往附件里放内容
    },
    handlevideoChange(res, file, key) {
      setTimeout(() => {
        this.formdata[key] = this.fileList = file.slice(-3)
      }, 1000)
      // if(file.raw.type == 'video/mp4'){
      //   setTimeout(() => {
      //     this.formdata[key] = file.response.data[0].address
      //     this.fileList = file.slice(-3);
      //   }, 1000);
      // }
    },// res, file
    handleexeclChange(res, file, key) {
      console.log("上传完毕",res)
      setTimeout(() => {
        // this.formdata['fileUrl']
        // this.formdata[key] = this.fileList = file.slice(-3)
        this.fileList = file
        // this.formdata[key] =
        const a = []
        const b = []
        this.fileList.forEach(item => {
            b.push(item.name)
            if (item.url) {
              a.push({name:item.name ,url: item.url}) // 放对象
            } else {
              // 遍历上传的data数据
              if(item.response.data && item.response.data.length>0){
                item.response.data.forEach(it=>{
                  a.push({name:item.name ,url: it.address.replace('\\', '/')})
                })
              }
            }
          }
        )
        this.formdata[key] = a
        this.formdata.fileName = b.join(',')
        console.log("文件集合",this.formdata[key])
        console.log("文件名称集合",this.formdata.fileName)
      }, 1000)
    },
    editorchange(val, key) {
      this.formdata[key] = val
    },
    handexeclleRemove(res, file, key) {
      // 数据赋值回去
      this.formdata[key] = file
      this.fileList = file
      console.log("数据this.fileList",this.fileList)
      console.log("数据集合",this.formdata[key])
      // 处理一下文件名称
      this.formdata.fileName = "";
      if(this.fileList && this.fileList.length>0){
        const b = []
        this.fileList.forEach(it=>{
          b.push(it.name)
        })
        this.formdata.fileName = b.join(',')
      }
      console.log("改变后的文件名称集合",this.formdata.fileName)
    },
    // 上传头像验证格式
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 200

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 200MB!')
      }
      return isJPG && isLt2M
    },
    // 头像上传成功
    handleAvatarSuccess(res, file, key) {
      this.formdata[key] = res.data[0].address.replace('\\', '/')
      this.picshow = true
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 多图上传成功
    handlemSuccess(res, file, key) {
      this.formdata[key].push(res.data[0].address.replace('\\', '/'))
    },
    handlemRemove(res, file, key) {
      this.formdata[key] = file
    },
    beforeUpload(file, fileList) { },
    beforemp4Upload(file) {
      const isVideo = file.type === 'video/mp4'
      if (!isVideo) {
        this.$message.error('请上传MP4文件')
      }
      return isVideo
    },
    handleChange(file, fileList, key) {
    },
    handleSuccess(res, file, fileList, key) {
      this.formdata[key] = res.data[0].address
      this.fliedata[key] = fileList
    },
    handleRemove(file, fileList) {
    },
    handlePreview(file) {
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      )
    },
    handlevideoExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    getData() {
      return this.$refs.ruleForm.validate().then((valid) => {
        if (valid) {
          const a = []
          const b = []
          this.fileList.forEach(item => {
            if (item.url) {
              a.push(item.url)
              b.push(item.name)
            } else {
              // 遍历上传的data数据
              if(item.response.data && item.response.data.length>0){
                item.response.data.forEach(it=>{
                  a.push(it.address.replace('\\', '/'))
                  b.push(item.name)
                })
              }
            }
          }
          )
          this.formdata.fileUrl = a.join(',')
          this.formdata.fileName = b.join(',')
          return this.formdata
        }
      })
    },
    resetForm() {
      this.isClear = true
      this.$refs.ruleForm.resetFields()
      // this.fliedata = {}
    },
    clearValidate() {
      this.$refs.ruleForm.clearValidate()
    }
  }
}
</script>
<style scoped>
.myDateStyle ::v-deep .el-input__inner {
    /*background-color: transparent !important;
    border-color:#80ffff;
    box-shadow: 1px 1px 5px 1px  RGB(128,255,255,0.8) inset;
    height: 30px;*/
    position: relative;
    z-index: 101;
}
.myDateStyle ::v-deep .el-picker-panel__content {
  width: 220px;
  height: 200px;
  margin-left: 0;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
